package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.WeChatProperties;
import com.zzyl.service.WechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {

    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public String getOpenId(String code) {
        //1. 发送请求调用微信接口
        // 1.1 封装参数请求
        Map<String, Object> params = new HashMap<>();
        params.put("appid", weChatProperties.getAppid());
        params.put("secret", weChatProperties.getSecret());
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");

        // 1.2 发送请求
        String body = HttpUtil.createGet("https://api.weixin.qq.com/sns/jscode2session")
                .form(params)
                .execute()
                .body();

        // 2 解析微信响应数据,
        JSONObject result = JSONUtil.parseObj(body);
        if (!result.containsKey("openid")){
            throw new BaseException(BasicEnum.GET_OPENID_ERROR);
        }
        return result.getStr("openid");
    }

    @Override
    public String getAccessToken() {
        //1 发送请求访问微信服务器获取授权访问令牌
        //1.1 封装请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("grant_type", "client_credential");
        params.put("appid", weChatProperties.getAppid());
        params.put("secret", weChatProperties.getSecret());
        //1.2 设置参数发送请求
        String body = HttpUtil.createGet("https://api.weixin.qq.com/cgi-bin/token")
                .form(params)
                .execute()
                .body();
        JSONObject result = JSONUtil.parseObj(body);
        if (!result.containsKey("access_token")){
            throw new BaseException(BasicEnum.GET_TOKEN_ERROR);
        }
        return result.getStr("access_token");
    }

    @Override
    public String getPhone(String access_token, String phoneCode, String openId) {
        // 1 发送请求访问微信服务器获取手机号
        // 1.1 构建请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("code", phoneCode);
        params.put("openid", openId);

        // 1.2 发送请求
        String body = HttpUtil.createPost("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token)
                // 设置json格式参数
                .body(JSONUtil.toJsonStr(params))
                .execute()
                .body();
        JSONObject result = JSONUtil.parseObj(body);
        if (!result.containsKey("phone_info")){
            throw new BaseException(BasicEnum.GET_PHONE_ERROR);
        }

        // 2 解析微信服务器的响应结果
        return result.getJSONObject("phone_info").getStr("phoneNumber");
    }
}